import React from 'react';
import { Row, Col, Button, Popconfirm, Form, InputNumber, Empty } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { ReloadOutlined, SettingOutlined } from '@ant-design/icons';
import { Bar, Pie, G2 } from '@ant-design/charts';

import { getCallAnalysisConversion, getCallAnalysisDuration } from 'admin/servers/servers';
import { percentAdjust } from '../../../../../utils';
G2.registerTheme('new-theme', {
  defaultColor: '#FF6B3B',
  colors10: [
    '#c4e5a6',
    '#60e160',
    '#389e0d',
    '#d4b105',
    '#e05f42',
    '#316dd9',
    '#bfbfbf',
    '#8CDAE5',
    '#B1ABF4',
    '#791DC9',
  ],
  colors20: [
    '#c4e5a6',
    '#60e160',
    '#389e0d',
    '#d4b105',
    '#e05f42',
    '#316dd9',
    '#bfbfbf',
    '#8CDAE5',
    '#B1ABF4',
    '#791DC9',

    '#117a7a',
    '#564db8',
    '#1D42C2',
    '#3c9cc2',
    '#D64BC0',
    '#255634',
    '#8C8C47',
    '#4bb7c5',
    '#8E283B',
    '#501980',
  ],
});
interface IProps {
  taskId: number;
}
interface IState {
  intervalTime: number;
  intervalCount: number;
  barTotal: number;
  barData: any;
  pieTotal: number;
  pieData: any;
  barLoading: boolean;
  pieLoading: boolean;
}
class CallAnalysis extends React.PureComponent<IProps, IState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;
  constructor(props: IProps) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.state = {
      intervalTime: 10,
      intervalCount: 7,
      barTotal: 0,
      barData: [],
      pieTotal: 0,
      pieData: [],
      barLoading: false,
      pieLoading: false,
    };
  }
  componentDidMount() {
    console.log('图表页-mount……');
    this.loadAnalysisDuration();
    this.loadAnalysisConversion();
  }

  private refresh() {
    console.log('图表页-refresh……');
    this.loadAnalysisDuration();
    this.loadAnalysisConversion();
  }
  /**加载（转化率分析）图表数据--饼图--pie */
  private loadAnalysisConversion() {
    this.setState({
      pieLoading: true,
    });
    getCallAnalysisConversion(this.props.taskId)
      .then(res => {
        console.log('加载pie……', res.data);
        if (res.data) {
          // *****mock数据---began
          // *****1.随机测试
          // let res = {
          //   code: 0,
          //   data: {
          //     total: 100, //总数
          //     degree0: Math.ceil(Math.random() * 100),
          //     degree1: Math.ceil(Math.random() * 100),
          //     degree2: Math.ceil(Math.random() * 100),
          //   },
          // };
          // *****2.特殊数值和测试
          // let res = {
          //   code: 0,
          //   data: {
          //     total: 100, //总数
          //     degree0: 33.3333,
          //     degree1: 33.3333,
          //     degree2: 33.3333,
          //   },
          // };
          // // mock总数
          // res.data.total = res.data.degree0 + res.data.degree1 + res.data.degree2;
          // *****mock数据---end
          const { total, degree0, degree1, degree2 } = res.data;
          if (!total) {
            return;
          }

          // 总数非0，才展示图表
          const arrList = [degree0, degree1, degree2];
          const pieData = [
            {
              item: '强烈意愿',
              count: degree2,
              rate: percentAdjust(arrList, 2, 1),
            },
            {
              item: '一般意愿',
              count: degree1,
              rate: percentAdjust(arrList, 1, 1),
            },
            {
              item: '无意愿',
              count: degree0,
              rate: percentAdjust(arrList, 0, 1),
            },
          ];

          this.setState({
            pieData: pieData,
            pieTotal: total,
            pieLoading: false,
          });
        } else {
          this.setState({
            pieLoading: false,
          });
        }
      })
      .catch(error => {
        this.setState({
          pieLoading: false,
        });
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }
  // 方便mock柱状图数据用
  private getRandomArrayElements(arr: any, count: number) {
    // eslint-disable-next-line prefer-const
    let shuffled = arr.slice(0),
      i = arr.length,
      // eslint-disable-next-line prefer-const
      min = i - count,
      temp,
      index;
    while (i-- > min) {
      index = Math.floor((i + 1) * Math.random());
      temp = shuffled[index];
      shuffled[index] = shuffled[i];
      shuffled[i] = temp;
    }
    return shuffled.slice(min);
  }
  /**加载（通话时长分析）图表数据--柱状图--bar */
  private loadAnalysisDuration() {
    this.setState({
      barLoading: true,
    });
    const { intervalTime, intervalCount } = this.state;
    console.log('请求-bar--入参：时间间隔', intervalTime, '区间个数', intervalCount);
    getCallAnalysisDuration(this.props.taskId, {
      intervalTime,
      intervalCount,
    })
      .then(res => {
        console.log('加载bar……', res.data);
        if (res.data) {
          const { count, talkTimeList } = res.data;
          // 数据转换前
          // *****mock数据---began
          // 举例：区间7个，间隔10s
          // *****1.随机数据测试
          // count = 80;
          // talkTimeList = [1, 38, 48, 65, 61, 12, 10, 52, 11, 23]; // 区间，由低到高
          // // 从上面数组随机生成
          // talkTimeList = this.getRandomArrayElements(talkTimeList, intervalCount);
          // *****2.特殊数值和测试
          // count = 100;
          // talkTimeList = [33.333, 33.333, 33.333]; // 区间，由低到高
          // *****mock数据---end
          if (!count) {
            return;
          }
          // 总数非0，才展示图表
          // 数据转换
          const barData = [];
          const len = talkTimeList.length;

          for (let i = 0; i < len; i++) {
            const text =
              i < len - 1
                ? `${i * intervalTime}-${(i + 1) * intervalTime}s`
                : `>${i * intervalTime}s`;
            // 倒序，填充横轴数据
            barData.unshift({
              time: text,
              value: talkTimeList[i],
              rate: percentAdjust(talkTimeList, i, 0), // 给barData添加百分比
            });
          }
          this.setState({
            barTotal: count,
            barData: barData,
            barLoading: false,
          });
        } else {
          this.setState({
            barLoading: false,
          });
        }
      })
      .catch(error => {
        this.setState({
          barLoading: false,
        });
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  private submitData(): void {
    const val = this.formRef.current?.getFieldsValue();
    const { intervalTime, intervalCount } = val;
    console.log('时间间隔', intervalTime, '区间个数', intervalCount);
    // 更改时间间隔和区间个数
    this.setState(
      {
        intervalTime: intervalTime || 10,
        intervalCount: intervalCount || 7,
      },
      () => {
        this.formRef.current?.resetFields();
        this.loadAnalysisDuration();
      }
    );
  }
  private close(): void {
    this.formRef.current?.resetFields();
  }
  render() {
    // debugger
    const {
      barData,
      barTotal,
      pieData,
      pieTotal,
      intervalTime,
      intervalCount,
      barLoading,
      pieLoading,
    } = this.state;

    const config_bar = {
      data: barData,
      xField: 'value',
      yField: 'time',
      seriesField: 'time',
      theme: 'new-theme',
      barWidthRatio: 0.35,
    };
    const config_pie = {
      padding: [0, 0, 0, 150],
      appendPadding: 10,
      data: pieData,
      colorField: 'item',
      angleField: 'count',
      radius: 0.9,
      color: ['#e05f42', '#316dd9', '#bfbfbf'],
    };

    console.log('图表分析-render-执行');
    return (
      <div className="call-analysis-area">
        {/* 刷新按钮 */}
        <Button
          className="refresh-btn"
          type="link"
          onClick={() => {
            this.refresh();
          }}
        >
          <ReloadOutlined style={{ fontSize: 22 }} />
        </Button>
        <Row>
          <Col md={22} lg={11}>
            {/* 柱状图展示 */}
            <div className="chart-bar-area">
              <div className="chart-tit">
                通话时长分析
                <Popconfirm
                  placement="bottomLeft"
                  icon={null}
                  onConfirm={() => this.submitData()}
                  onCancel={() => this.close()}
                  okText="确定"
                  cancelText="取消"
                  title={
                    <Form
                      style={{ marginLeft: '-20px' }}
                      layout="horizontal"
                      ref={this.formRef}
                      initialValues={{
                        intervalTime: intervalTime,
                        intervalCount: intervalCount,
                      }}
                    >
                      <Form.Item label="区间间隔" name="intervalTime">
                        <InputNumber
                          className="input-number"
                          min={1}
                          max={200}
                          precision={0}
                          formatter={value => `${value}秒`}
                          parser={(value: any) => {
                            return value.replace('秒', '');
                          }}
                        />
                      </Form.Item>
                      <Form.Item label="区间个数" name="intervalCount">
                        <InputNumber className="input-number" min={1} max={10} precision={0} />
                      </Form.Item>
                    </Form>
                  }
                >
                  <Button className="operate-btn" type="link">
                    <SettingOutlined style={{ fontSize: 22 }} />
                  </Button>
                </Popconfirm>
              </div>
              <div className="chart-area">
                {!barTotal && (
                  <div className="chart-noData-bar">
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} imageStyle={{ height: 100 }} />
                  </div>
                )}
                {barTotal > 0 && (
                  <Bar
                    loading={barLoading}
                    {...config_bar}
                    height={300}
                    padding={[16, 60, 16, 60]}
                    legend={false}
                    label={{
                      position: 'right',
                      style: {
                        fill: '#333',
                        fontSize: 14,
                      },
                      formatter: ({ rate }) => {
                        return rate + '%';
                      },
                    }}
                    xAxis={{
                      label: {
                        // 返回空字符串 隐藏横坐标文字内容
                        formatter: text => '',
                      },
                      grid: {
                        line: {
                          style: {
                            stroke: 'transparent',
                          },
                        },
                      },
                    }}
                    yAxis={{
                      line: null,
                      tickLine: null,
                    }}
                    tooltip={{
                      showTitle: false,
                      formatter: ({ time, value }) => {
                        return { name: '通话时长' + time, value: value + '次' };
                      },
                    }}
                  />
                )}
              </div>
            </div>
          </Col>
          <Col md={22} lg={11} offset={1}>
            {/* 饼图展示 */}
            <div className="chart-pie-area">
              <div className="chart-tit">转化率分析</div>
              <div className="chart-area">
                {!pieTotal && (
                  <div className="chart-noData-pie">
                    <Empty
                      className="special-empty"
                      image="/webapp/no-pie-data.png"
                      imageStyle={{ height: 300, margin: 20, paddingRight: 10 }}
                      description="抱歉，你的流程未配置意向"
                    />
                  </div>
                )}
                {pieTotal > 0 && (
                  <ul className="custom-legend">
                    <li className="level2">
                      {pieData[0].item} {pieData[0].count}
                      <div>{pieData[0].rate}%</div>
                    </li>
                    <li className="level1">
                      {pieData[1].item} {pieData[1].count}
                      <div>{pieData[1].rate}%</div>
                    </li>
                    <li className="level0">
                      {pieData[2].item} {pieData[2].count}
                    </li>
                  </ul>
                )}
                {pieTotal > 0 && (
                  <Pie
                    animation={{
                      appear: {
                        animation: 'fadeIn',
                        easing: 'easeQuadIn',
                        delay: 300, // 动画延迟执行时间
                        duration: 600, // 动画执行时间
                      },
                      enter: {
                        animation: 'fadeIn',
                        easing: 'easeQuadIn',
                        delay: 300, // 动画延迟执行时间
                        duration: 600, // 动画执行时间
                      },
                    }}
                    loading={pieLoading}
                    {...config_pie}
                    height={300}
                    legend={false}
                    label={false}
                  />
                )}
              </div>
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}

export default CallAnalysis;
